﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Async2._1
{
    class Program
    {
        static async Task Main(string[] args)
        {
            //Console.WriteLine("主线程ID: " + Thread.CurrentThread.ManagedThreadId);
            //string content = await DownloadStringWithRetries("https://www.baidu.com");
            string content = await DownloadStringWithTimeout("https://www.baidu.com");
            Console.WriteLine(content);
            Console.ReadKey();
        }

        static async Task<string> DownloadStringWithRetries(string url)
        {
            using (var client = new HttpClient())
            {
                var nextDelay = TimeSpan.FromSeconds(1);
                for (int i = 0; i != 3; ++i)
                {
                    try
                    {
                        return await client.GetStringAsync(url);
                    }
                    catch
                    { }
                    await Task.Delay(nextDelay);
                    nextDelay = nextDelay + nextDelay;
                }
                return await client.GetStringAsync(url);
            }
        }

        static async Task<string> DownloadStringWithTimeout(string url)
        {
            using (var client = new HttpClient())
            {
                var downloadTask = client.GetStringAsync(url);
                var timeoutTask = Task.Delay(3000);

                var completedTask = await Task.WhenAny(downloadTask, timeoutTask);
                if (completedTask == timeoutTask)
                    return null;
                return await downloadTask;
            }
        }
    }
}
